package com.example.myapplication.part12;

import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.R;

import java.util.List;

public class FlowerAdapter extends RecyclerView.Adapter<FlowerAdapter.ViewHolder> {

    private List<Flower> mFlowerList;

    static class ViewHolder extends RecyclerView.ViewHolder {
        View flowerView;
        ImageView flowerImage;
        TextView flowerName;

        public ViewHolder(View view) {
            super(view);
            flowerView = view;
            flowerImage = view.findViewById(R.id.flower_image);
            flowerName = view.findViewById(R.id.flower_name);
        }
    }

    public FlowerAdapter(List<Flower> flowerList) {
        mFlowerList = flowerList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.flower_item, parent, false);
        final ViewHolder holder = new ViewHolder(view);

        // 设置点击事件
        holder.flowerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    Flower flower = mFlowerList.get(position);
                    Toast.makeText(v.getContext(), "You clicked view: " + flower.getName(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        holder.flowerImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    Flower flower = mFlowerList.get(position);
                    Toast.makeText(v.getContext(), "You clicked image: " + flower.getName(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Flower flower = mFlowerList.get(position);
        holder.flowerImage.setImageResource(flower.getImageId());
        holder.flowerName.setText(flower.getName());
    }

    @Override
    public int getItemCount() {
        return mFlowerList == null ? 0 : mFlowerList.size();
    }
}

